package cn.com.libertymutual.sp.service.impl;

import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.com.libertymutual.core.util.Constants;
import cn.com.libertymutual.core.util.DateUtil;
import cn.com.libertymutual.core.web.ServiceResult;
import cn.com.libertymutual.sp.bean.TbSpOtherPlatform;
import cn.com.libertymutual.sp.dao.TbSpOtherPlatformDao;
import cn.com.libertymutual.sp.service.api.ApplyInsureService;

@Service("ApplyInsureService")
public class ApplyInsureServiceImpl implements ApplyInsureService {

	@Autowired
	private TbSpOtherPlatformDao platformDao;

	@Override
	public ServiceResult platformInsure(HttpServletRequest request, HttpServletResponse response, ServiceResult sr, String imgCode, String mobileCode,
			String nickName, String email, String mobile) {

		if (StringUtils.isBlank(nickName)) {
			sr.setResult("请输入称呼内容");
			return sr;
		}
		if (StringUtils.isBlank(email)) {
			sr.setResult("请输入邮箱地址");
			return sr;
		}
		Pattern p = Pattern.compile(Constants.REGEX_SPECIALCHARACTERS_CODE);
		Matcher m = p.matcher(nickName);
		if (m.find()) {
			sr.setResult("称呼名称不能包含特殊字符");
			return sr;
		}
		if (nickName.length() < 2) {
			sr.setResult("称呼名称过短");
			return sr;
		}
		if (nickName.length() > 20) {
			sr.setResult("称呼名称过长");
			return sr;
		}
		if (email.length() > 100) {
			sr.setResult("邮箱地址过长");
			return sr;
		}

		String upMonth = DateUtil.dateAdd(2, -1, DateUtil.getStringDate());// 获取上一个月的当前时间
		List<TbSpOtherPlatform> otherPlatforms = platformDao.findByTime(email, mobile, DateUtil.getDateByString(upMonth));
		if (CollectionUtils.isNotEmpty(otherPlatforms)) {
			sr.setResult("最近一个月内您已申请过");
			return sr;
		}

		TbSpOtherPlatform platform = new TbSpOtherPlatform();
		platform.setNickName(nickName);
		platform.setEmail(email);
		platform.setMobile(mobile);
		platform.setCreateTime(new Date());

		platformDao.save(platform);

		sr.setResult(platform);
		sr.setSuccess();

		return sr;
	}
}
